package de.metalcon.gwt.client.interactions;

import java.util.HashMap;

import com.google.gwt.user.client.Window;

import de.metalcon.gwt.client.rpc.AsyncTransmitterCallback;
import de.metalcon.gwt.client.rpc.ContentTransmitterHandler;
import de.metalcon.gwt.shared.ContentTransmitter;

public abstract class ADynamicModule extends AInteraction {
	HashMap<String, Object> requestVars = new HashMap<String, Object>();
	private ContentTransmitter t;

	public ADynamicModule() {
		startLoading();
		load();
	}

	protected void addReuqestVar(String key, Object value) {
		requestVars.put(key, value);
	}

	private String getUniqueKey() {
		return getModuleName() + requestVars.hashCode();
	}

	private String getModuleName() {
		String fullName = getClass().getName();
		return fullName.substring(fullName.lastIndexOf(".") + 1);
	}

	private void load() {
		ContentTransmitterHandler.getTransmitter(getModuleName(), getUniqueKey(), requestVars, new AsyncTransmitterCallback<ContentTransmitter>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());
			}

			@Override
			public void afterSuccess(ContentTransmitter result) {
				if (result != null) {
					stopLoading();
					t = result;
					generateContent();
				} else {
					// setPage(new State404());
				}
			}
		});
	}

	protected ContentTransmitter getContentTransmitter() {
		return t;
	}

	private void startLoading() {

	}

	private void stopLoading() {

	}
}
